package com.hongqianping.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hongqianping.entity.BuserTable;
import com.hongqianping.entity.CartTable;
import com.hongqianping.entity.GoodsTable;
import com.hongqianping.entity.GoodsType;
import com.hongqianping.entity.OrderBaseTable;
import com.hongqianping.entity.OrderDetail;
import com.hongqianping.service.CartTableService;
import com.hongqianping.service.GoodsTableService;
import com.hongqianping.service.GoodsTypeService;
import com.hongqianping.service.OrderBaseTableService;
import com.hongqianping.service.OrderDetailService;

import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Controller
public class OrderController {

    @Autowired
    private OrderBaseTableService orderBaseTableService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private CartTableService cartTableService;

    @Autowired
    private GoodsTableService goodsTableService;

    @Autowired
    private GoodsTypeService goodsTypeService;

    @PostMapping("/checkout")
    public String checkout(HttpSession session, Model model) {
        BuserTable currentUser = (BuserTable) session.getAttribute("currentUser");
        if (currentUser == null) {
            return "redirect:/login.html";
        }

        // 获取导航栏所有商品类型
        List<GoodsType> goodsTypes = goodsTypeService.list();
        model.addAttribute("goodsTypes", goodsTypes);

        // 获取购物车商品
        LambdaQueryWrapper<CartTable> cartQueryWrapper = new LambdaQueryWrapper<>();
        cartQueryWrapper.eq(CartTable::getBusertableId, currentUser.getId());
        List<CartTable> cartItems = cartTableService.list(cartQueryWrapper);

        if (cartItems.isEmpty()) {
            model.addAttribute("error", "购物车为空，无法结算！");
            return "redirect:/cart";
        }

        // 计算总金额并准备订单详情
        double totalAmount = 0.0;
        List<Map<String, Object>> cartDetails = new ArrayList<>();

        for (CartTable item : cartItems) {
            GoodsTable goods = goodsTableService.getById(item.getGoodstableId());
            if (goods == null) {
                model.addAttribute("error", "购物车中包含无效商品！");
                return "redirect:/cart";
            }
            if (goods.getGstore() < item.getShoppingnum()) {
                model.addAttribute("error", "商品 " + goods.getGname() + " 库存不足！");
                return "redirect:/cart";
            }

            double subtotal = goods.getGrprice() * item.getShoppingnum();
            totalAmount += subtotal;

            Map<String, Object> cartEntry = new HashMap<>();
            cartEntry.put("goods", goods);
            cartEntry.put("shoppingNum", item.getShoppingnum());
            cartEntry.put("subtotal", subtotal);
            cartDetails.add(cartEntry);
        }

        model.addAttribute("cartDetails", cartDetails);
        model.addAttribute("totalAmount", totalAmount);
        return "checkout";
    }

    @PostMapping("/placeOrder")
    @Transactional
    @ResponseBody
    public ResponseEntity<Map<String, Object>> placeOrder(HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        BuserTable currentUser = (BuserTable) session.getAttribute("currentUser");
        if (currentUser == null) {
            response.put("success", false);
            response.put("message", "请先登录！");
            return new ResponseEntity<>(response, HttpStatus.UNAUTHORIZED);
        }

        LambdaQueryWrapper<CartTable> cartQueryWrapper = new LambdaQueryWrapper<>();
        cartQueryWrapper.eq(CartTable::getBusertableId, currentUser.getId());
        List<CartTable> cartItems = cartTableService.list(cartQueryWrapper);

        if (cartItems.isEmpty()) {
            response.put("success", false);
            response.put("message", "购物车为空，无法下单！");
            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        }

        double totalAmount = 0.0;
        List<OrderDetail> orderDetailsToSave = new ArrayList<>();

        for (CartTable item : cartItems) {
            GoodsTable goods = goodsTableService.getById(item.getGoodstableId());
            if (goods == null) {
                response.put("success", false);
                response.put("message", "购物车中包含无效商品！");
                return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
            }
            if (goods.getGstore() < item.getShoppingnum()) {
                response.put("success", false);
                response.put("message", "商品 \"" + goods.getGname() + "\" 库存不足！");
                return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
            }
            totalAmount += goods.getGrprice() * item.getShoppingnum();

            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setGoodstableId(item.getGoodstableId());
            orderDetail.setShoppingnum(item.getShoppingnum());
            orderDetailsToSave.add(orderDetail);

            goods.setGstore(goods.getGstore() - item.getShoppingnum());
            goodsTableService.updateById(goods);
        }

        OrderBaseTable orderBase = new OrderBaseTable();
        orderBase.setBusertableId(currentUser.getId());
        orderBase.setAmount(totalAmount);
        orderBase.setStatus(0); // 0表示待支付
        orderBase.setOrderdate(LocalDateTime.now());
        orderBaseTableService.save(orderBase);

        for (OrderDetail detail : orderDetailsToSave) {
            detail.setOrderbasetableId(orderBase.getId());
        }
        orderDetailService.saveBatch(orderDetailsToSave);

        cartTableService.remove(cartQueryWrapper);

        response.put("success", true);
        response.put("message", "订单创建成功！");
        response.put("orderId", orderBase.getId());
        return new ResponseEntity<>(response, HttpStatus.OK);
    }

    @GetMapping("/orders")
    public String viewOrders(HttpSession session, Model model) {
        BuserTable currentUser = (BuserTable) session.getAttribute("currentUser");
        if (currentUser == null) {
            return "redirect:/login.html";
        }

        // 获取导航栏所有商品类型
        List<GoodsType> goodsTypes = goodsTypeService.list();
        model.addAttribute("goodsTypes", goodsTypes);

        LambdaQueryWrapper<OrderBaseTable> orderBaseQueryWrapper = new LambdaQueryWrapper<>();
        orderBaseQueryWrapper.eq(OrderBaseTable::getBusertableId, currentUser.getId())
                           .orderByDesc(OrderBaseTable::getOrderdate);
        List<OrderBaseTable> orders = orderBaseTableService.list(orderBaseQueryWrapper);

        // 对于订单列表页面，我们只需要基本的订单信息。
        // 各个订单详情将通过单独的端点获取。
        model.addAttribute("orders", orders); // 直接传递OrderBaseTable列表

        return "orders"; // 这将渲染 orders.html
    }

    // 用于显示单个订单详情的新方法
    @GetMapping("/order/detail/{orderId}")
    public String viewOrderDetail(@PathVariable("orderId") Long orderId, HttpSession session, Model model) {
        BuserTable currentUser = (BuserTable) session.getAttribute("currentUser");
        if (currentUser == null) {
            return "redirect:/login.html";
        }

        // 获取导航栏所有商品类型
        List<GoodsType> goodsTypes = goodsTypeService.list();
        model.addAttribute("goodsTypes", goodsTypes);

        OrderBaseTable orderBase = orderBaseTableService.getById(orderId);
        // 确保订单属于当前用户
        if (orderBase == null || !orderBase.getBusertableId().equals(currentUser.getId())) {
            model.addAttribute("error", "订单不存在或您无权查看！");
            return "redirect:/orders"; // 重定向到订单列表或错误页面
        }

        LambdaQueryWrapper<OrderDetail> orderDetailQueryWrapper = new LambdaQueryWrapper<>();
        orderDetailQueryWrapper.eq(OrderDetail::getOrderbasetableId, orderId);
        List<OrderDetail> orderDetails = orderDetailService.list(orderDetailQueryWrapper);

        List<Map<String, Object>> orderItems = new ArrayList<>();
        for (OrderDetail detail : orderDetails) {
            GoodsTable goods = goodsTableService.getById(detail.getGoodstableId());
            if (goods != null) {
                Map<String, Object> item = new HashMap<>();
                item.put("goods", goods);
                item.put("shoppingNum", detail.getShoppingnum());
                item.put("subtotal", goods.getGrprice() * detail.getShoppingnum());
                orderItems.add(item);
            }
        }

        model.addAttribute("orderBase", orderBase);
        model.addAttribute("orderItems", orderItems);
        return "order_detail"; // 这将渲染新的 order_detail.html
    }

    @PostMapping("/order/pay/{orderId}")
    @ResponseBody
    @Transactional
    public ResponseEntity<Map<String, Object>> payOrder(@PathVariable("orderId") Long orderId, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        BuserTable currentUser = (BuserTable) session.getAttribute("currentUser");

        if (currentUser == null) {
            response.put("success", false);
            response.put("message", "请先登录！");
            return new ResponseEntity<>(response, HttpStatus.UNAUTHORIZED);
        }

        OrderBaseTable orderBase = orderBaseTableService.getById(orderId);
        if (orderBase == null || !orderBase.getBusertableId().equals(currentUser.getId())) {
            response.put("success", false);
            response.put("message", "订单不存在或无权操作！");
            return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
        }

        if (orderBase.getStatus() == 1) { // 1表示已支付
            response.put("success", false);
            response.put("message", "订单已支付，请勿重复操作！");
            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        }

        // 假设这里是支付逻辑，实际应用中会调用支付接口
        orderBase.setStatus(1); // 将订单状态设置为已支付
        boolean updated = orderBaseTableService.updateById(orderBase);

        if (updated) {
            response.put("success", true);
            response.put("message", "订单支付成功！");
            return new ResponseEntity<>(response, HttpStatus.OK);
        } else {
            response.put("success", false);
            response.put("message", "订单支付失败，请稍后再试！");
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
} 